package com.cn.shuangzi.ad.custom;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.mediation.ad.IMediationDislikeCallback;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdDislike;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationViewBinder;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.native_ad.MediationCustomNativeAd;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomNativeDislikeDialog;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.util.SZImageLoader;
import com.cn.shuangzi.util.SZUtil;
import com.kwad.components.core.internal.api.KSAdVideoPlayConfigImpl;
import com.kwad.sdk.api.KsImage;
import com.kwad.sdk.api.KsNativeAd;
import com.kwad.sdk.api.model.AdSourceLogoType;
import com.kwad.sdk.api.model.InteractionType;
import com.kwad.sdk.api.model.MaterialType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 快手 信息流 开发者自渲染（自渲染）广告对象
 */
public class KsFeedNativeAd extends MediationCustomNativeAd {


    private KsNativeAd mKsNativeAd;
    private Context mContext;
    private SZImageLoader imageLoader;
    public KsFeedNativeAd(Context context, KsNativeAd ksNativeAd) {

        ADManager.getInstance().setKsNativeAd(ksNativeAd);
        this.mKsNativeAd = ksNativeAd;
        this.mContext = context;
        this.setActionText(mKsNativeAd.getActionDescription());
        this.setDescription(ksNativeAd.getAdDescription()); //描述
        this.setIconUrl(ksNativeAd.getAppIconUrl());
        String appName = !TextUtils.isEmpty(mKsNativeAd.getAppName()) ? ksNativeAd.getAppName() :
                !TextUtils.isEmpty(ksNativeAd.getProductName()) ? ksNativeAd.getProductName() : "";
        this.setSource(appName); // appName
        this.setTitle(ksNativeAd.getAdSource()); // appName
        this.setExpressAd(false);
        this.setStarRating(ksNativeAd.getAppScore());
        if (ksNativeAd.getInteractionType() == InteractionType.DOWNLOAD) {
            this.setInteractionType(TTAdConstant.INTERACTION_TYPE_DOWNLOAD);
        } else if (ksNativeAd.getInteractionType() == InteractionType.H5) {
            this.setInteractionType(TTAdConstant.INTERACTION_TYPE_LANDING_PAGE);
        } else {
            this.setInteractionType(TTAdConstant.INTERACTION_TYPE_UNKNOWN);
        }

        if (ksNativeAd.getMaterialType() == MaterialType.SINGLE_IMG) {
            if (ksNativeAd.getImageList() != null && !ksNativeAd.getImageList().isEmpty() && ksNativeAd.getImageList().get(0) != null) {
                this.setAdImageMode(TTAdConstant.IMAGE_MODE_LARGE_IMG);
                KsImage image = ksNativeAd.getImageList().get(0);
                this.setImageUrl(image.getImageUrl());
                this.setImageHeight(image.getHeight());
                this.setImageWidth(image.getWidth());
            }
        } else if (ksNativeAd.getMaterialType() == MaterialType.GROUP_IMG) {
            if (ksNativeAd.getImageList() != null && ksNativeAd.getImageList().size() > 0) {
                this.setAdImageMode(TTAdConstant.IMAGE_MODE_GROUP_IMG);
                List<String> images = new ArrayList<>();
                for (KsImage image : ksNativeAd.getImageList()) {
                    images.add(image.getImageUrl());
                }
                this.setImageList(images);
            }
        } else if (ksNativeAd.getMaterialType() == MaterialType.VIDEO) {
            this.setAdImageMode(TTAdConstant.IMAGE_MODE_VIDEO);
            KsImage videoImg = ksNativeAd.getVideoCoverImage();
            if (videoImg == null) {
                // videoCoverImage为空的话，用imageList做兜底
                if (ksNativeAd.getImageList() != null && !ksNativeAd.getImageList().isEmpty() && ksNativeAd.getImageList().get(0) != null) {
                    videoImg = ksNativeAd.getImageList().get(0);
                }
            }
            if (videoImg != null) {
                this.setImageUrl(videoImg.getImageUrl());
                this.setImageHeight(videoImg.getHeight());
                this.setImageWidth(videoImg.getWidth());
            }
        } else {
            this.setAdImageMode(TTAdConstant.IMAGE_MODE_UNKNOWN);
        }
        mKsNativeAd.setVideoPlayListener(mVideoPlayListener);
    }

    /**
     * 视频播放回调
     */
    KsNativeAd.VideoPlayListener mVideoPlayListener = new KsNativeAd.VideoPlayListener() {
        @Override
        public void onVideoPlayReady() {

        }

        @Override
        public void onVideoPlayStart() {
            SZUtil.log("快手自定义信息流，onVideoStart");
            callVideoStart();
        }

        @Override
        public void onVideoPlayComplete() {
            SZUtil.log("快手自定义信息流，onVideoCompleted");
            callVideoCompleted();
        }

        @Override
        public void onVideoPlayError(int i, int i1) {
            SZUtil.log("快手自定义信息流，onVideoError errorCode = " + i + " errorMessage = " + i1);
            callVideoError(i, null);

        }

        @Override
        public void onVideoPlayPause() {
            SZUtil.log("快手自定义信息流，onVideoPause");
            callVideoPause();
        }

        @Override
        public void onVideoPlayResume() {
            SZUtil.log("快手自定义信息流，onVideoResume");
            callVideoResume();
        }
    };

    KsNativeAd.AdInteractionListener mAdInteractionListener = new KsNativeAd.AdInteractionListener() {
        @Override
        public void onAdClicked(View view, KsNativeAd ksNativeAd) {
            SZUtil.log("快手自定义信息流，onADClicked");
            callAdClick();
        }

        @Override
        public void onAdShow(KsNativeAd ksNativeAd) {
            SZUtil.log("快手自定义信息流，onADExposed");
            callAdShow();
            setDislikeDialogCallBack(new MediationCustomNativeDislikeDialog() {
                @Override
                public MediationAdDislike getDislikeDialog(Activity activity, Map<String, Object> extra) {
                    return new MediationAdDislike() {
                        @Override
                        public void showDislikeDialog() {

                        }

                        @Override
                        public void setDislikeCallback(IMediationDislikeCallback dislikeCallback) {

                        }
                    };
                }

                @Override
                public void dislikeClick(String disLikeInfo, Map<String, Object> extra) {

                }
            });

        }

        /*
         * @return  返回为true, 则只会给媒体弹出回调，SDK的默认弹窗逻辑不会执行
         * @return  返回为false, 则使用SDK默认的合规弹窗。
         * 弹出弹窗dialog后， 用户确认下载，则媒体需要回调 OnClickListener.onClick(dialog, DialogInterface
         * .BUTTON_POSITIVE)
         * 弹出弹窗dialog后， 用户点击取消，则媒体需要回调 OnClickListener.onClick(dialog, DialogInterface
         * .BUTTON_NEGATIVE)
         * */
        @Override
        public boolean handleDownloadDialog(DialogInterface.OnClickListener onClickListener) {
            return false;
        }

        @Override
        public void onDownloadTipsDialogShow() {
            // 广告展示下载合规弹窗
        }

        @Override
        public void onDownloadTipsDialogDismiss() {
            // 广告关闭下载合规弹窗
        }
    };

    @Override
    public void registerView(Activity activity, ViewGroup container, List<View> clickViews, List<View> creativeViews, List<View> directDownloadViews, MediationViewBinder viewBinder) {
        super.registerView(activity, container, clickViews, creativeViews, directDownloadViews, viewBinder);
        if (clickViews != null && creativeViews != null) {
            clickViews.addAll(creativeViews);
        }
        if (container instanceof FrameLayout) {
            if (mKsNativeAd != null) {
                mKsNativeAd.registerViewForInteraction(container, clickViews, mAdInteractionListener);
            }

            if (mKsNativeAd != null && mKsNativeAd.getAdSourceLogoUrl(AdSourceLogoType.GREY) != null) {
                View logoView = container.findViewById(viewBinder.logoLayoutId);
                if (logoView != null) {
                    logoView.setVisibility(View.VISIBLE);
                    if (logoView instanceof ViewGroup) {
                        ((ViewGroup) logoView).removeAllViews();
                        ImageView logo = new ImageView(mContext);
                        if(imageLoader == null){
                            imageLoader = new SZImageLoader(mContext);
                        }
                        logo.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        imageLoader.load(logo,mKsNativeAd.getAdSourceLogoUrl(1));
//                        DownloadImageTask logoImgTask = new DownloadImageTask(logo);
//                        logoImgTask.execute(mKsNativeAd.getAdSourceLogoUrl(1));
                        ((ViewGroup) logoView).addView(logo, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    } else if (logoView instanceof ImageView) {

                        ImageView logo = (ImageView) logoView;
                        if(imageLoader == null){
                            imageLoader = new SZImageLoader(mContext);
                        }
                        logo.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        imageLoader.load(logo,mKsNativeAd.getAdSourceLogoUrl(1));
//                        DownloadImageTask logoImgTask = new DownloadImageTask(((ImageView) logoView));
//                        logoImgTask.execute(mKsNativeAd.getAdSourceLogoUrl(1));
//                        ((ImageView) logoView).setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    }
                }
            }

            // 如果开发者选择自己进行视频播放处理，则这里不处理视频view。但如果videoUrl是空，则兜底还用adn自己的视频播放
            if (!isUseCustomVideo() || mKsNativeAd == null || TextUtils.isEmpty(mKsNativeAd.getVideoUrl())) {
                FrameLayout mediaView = container.findViewById(viewBinder.mediaViewId);
                if (mKsNativeAd != null && mediaView != null) {
                    KSAdVideoPlayConfigImpl playConfig = new KSAdVideoPlayConfigImpl();
                    playConfig.setVideoSoundEnable(true);
                    View videoView = mKsNativeAd.getVideoView(mContext, playConfig);
                    if (videoView == null) {
                        return;
                    }
                    removeSelfFromParent(videoView);
                    mediaView.removeAllViews();
                    mediaView.addView(videoView, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                }
            }
        }
    }

    public void removeSelfFromParent(View child) {
        try {
            if (child != null) {
                ViewParent parent = child.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    ((ViewGroup) parent).removeView(child);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getVideoUrl() {
        return "video url";
    }

    @Override
    public TTFeedAd.CustomizeVideo getNativeCustomVideoReporter() {
        return new TTFeedAd.CustomizeVideo() {
            @Override
            public String getVideoUrl() {
                return null;
            }

            @Override
            public void reportVideoStart() {
                SZUtil.log("快手自定义信息流，reportVideoStart");
            }

            @Override
            public void reportVideoPause(long playingTime) {
                SZUtil.log("快手自定义信息流，reportVideoPause");
            }

            @Override
            public void reportVideoContinue(long playingTime) {
                SZUtil.log("快手自定义信息流，reportVideoContinue");
            }

            @Override
            public void reportVideoFinish() {
                SZUtil.log("快手自定义信息流，reportVideoFinish");
            }

            @Override
            public void reportVideoBreak(long playingTime) {
                SZUtil.log("快手自定义信息流，reportVideoBreak");
            }

            @Override
            public void reportVideoAutoStart() {
                SZUtil.log("快手自定义信息流，reportVideoAutoStart");
            }

            @Override
            public void reportVideoStartError(int errorCode, int extra) {
                SZUtil.log("快手自定义信息流，reportVideoStartError");
            }

            @Override
            public void reportVideoError(long playingTime, int errorCode, int extra) {
                SZUtil.log( "快手自定义信息流，reportVideoError");
            }
        };
    }

    @Override
    public boolean hasDislike() {
        SZUtil.log("快手自定义信息流，hasDislike");
        return true;
    }

    @Override
    public void onPause() {
        SZUtil.log("快手自定义信息流，onPause");
        super.onPause();
    }

    @Override
    public void onResume() {
        SZUtil.log("快手自定义信息流，onResume");
        super.onResume();
    }

    @Override
    public void onDestroy() {
        SZUtil.log("快手自定义信息流，onDestroy");
        super.onDestroy();
    }
}